package forgeAPI

import (
	"github.com/kirinlabs/HttpRequest"
	"github.com/rs/xid"
	"log"
	"encoding/json"
	"encoding/base64"
	"os"
	"os/exec"
	"io"
	"net/url"
	"io/ioutil"
	"strconv"
	"strings"
	"net/http"
	"path"
	"errors"
	"bufio"
	//"fmt"
)

var (
	clientId = ""
	clientSecret = ""
	svfUnzipFolder = ""
	ForgeServer = "https://developer.api.autodesk.com/derivativeservice/v2/derivatives"
	ForgeAPIServer = "https://developer.api.autodesk.com/modelderivative/v2/designdata"	
	ForgeTokenServer = "https://developer.api.autodesk.com/authentication/v1/authenticate"
	ForgeBucketServer = "https://developer.api.autodesk.com/oss/v2/buckets"	      
)

type ForgeSVFManifest struct {
	Name string `json:"name"`
	Toolkitversion string `json:"toolkitversion"`
	Manifestversion string `json:"manifestversion"`
	AdskID interface{} `json:"adskID"`
	Assets []ForgeSVFManifestAsset `json:"assets"`
}

type ForgeSVFManifestAsset struct {
	Id string `json:"id"`
	Type string `json:"type"`
	Typeset string `json:"typeset"`
	URI string `json:"URI"`
	Size string `json:"size"`
	Usize string `json:"usize"`
}

type ForgeManifestResult struct {
	Type string `json:"type"`
	HasThumbnail string `json:"hasThumbnail"`
	Status string `json:"status"`
	Progress string `json:"progress"`
	Region string `json:"region"`
	Urn string `json:"urn"`
	Version string `json:"version"`
	Derivatives []struct {
		Status string `json:"status"`
		Progress string `json:"progress"`
		OutputType string `json:"outputType"`
		Role string `json:"role"`
		Children []struct{
			Guid string `json:"guid"`
			Type string `json:"type"`
			Role string `json:"role"`
			Urn string `json:"urn"`
			Resolution []int `json:"resolution"`
			Mime string `json:"mime"`
			Status string `json:"status"`
			Name string `json:"name"`
			ViewableID string `json:"viewableID"`
			PhaseNames string `json:"phaseNames"`
			HasThumbnail string `json:"hasThumbnail"`
			Progress string `json:"progress"`
			Children []struct {
				Guid string `json:"guid"`
				Type string `json:"type"`
				Role string `json:"role"`
				Name string `json:"name"`
				Status string `json:"status"`
				Progress string `json:"progress"`
				Camera []float32 `json:"camera"`
				Urn string `json:"urn"`
				Mime string `json:"mime"`
				Resolution []int `json:"resolution"`
			}
		}
		Messages interface {} `json:"messages"`
	}
}

type ForgeUpdateResult struct{
	BucketKey string `json:"bucketKey"`
	ObjectId string `json:"objectId"`
	ObjectKey string `json:"objectKey"`
	Sha1 string `json:"sha1"`
	Size string `json:"size"`
	ContentType string `json:"contentType"`
	Location string `json:"location"`
}

type ForgeTranslateResult struct {
	Result string `json:"result"` 
	Urn string `json:"urn"`
	RegisterKeys []string `json:"registerKeys"`
	AcceptedJobs interface{} `json:"acceptedJobs"`
}

// 初始化 clientId 和 clientSecret
func Init(cId string, cSecret string){
	clientId = cId
	clientSecret = cSecret
}

// base64安全转换
func Base64UrlSafeEncode(source []byte) string  {
	bytearr := base64.StdEncoding.EncodeToString(source)
	safeurl := strings.Replace(string(bytearr), "/", "_", -1)
	safeurl = strings.Replace(safeurl, "+", "-", -1)
	safeurl = strings.Replace(safeurl, "=", "", -1)
	return safeurl
}

// 转换 encodeURI
func EncodeURIComponent(str string) string {
	r := url.QueryEscape(str)
	r = strings.Replace(r, "+", "%20", -1)
	return r
}

// 路径是否存在
func PathExists(path string) (bool, error)  {
	_, err := os.Stat(path)
	if err == nil {
		return true, nil
	}
	if os.IsNotExist(err) {
		return false, nil
	}
	return false, err
}

// 切分Durn
func SplitDUrn (durn string) (string, string, string) {
	if durn == "" {
		return "", "", ""
	}

	durnArray := strings.Split(durn, "/")
	
	var baseUrn = durnArray[0]
	basePath := strings.Join(durnArray[1:len(durnArray)-1],"/")
	var svfFile = durnArray[len(durnArray) -1 ]
	return baseUrn, basePath, svfFile 
}

// 获取token
func GetToken(scope string) (string, error) {
	var token string
	req := HttpRequest.NewRequest()
	req.SetHeaders(map[string]string{
		"content-type": "application/x-www-form-urlencoded",
	})
	resp, err := req.Post(ForgeTokenServer, map[string]interface{}{
		"client_id":clientId,
		"client_secret":clientSecret,
		"grant_type":"client_credentials",
		"scope":scope,
	})

	if err != nil {
		return token, err
	}
	
	//log.Println("GetToken resp.StatusCode()", resp.StatusCode())
	if resp.StatusCode() == 200 {
		body, err := resp.Body()
		
		if err != nil {
			return token, err
		}

		var dat map[string]interface{}
		json.Unmarshal([]byte(body), &dat)
		token = dat["access_token"].(string)
		return token, nil
	} else if resp.StatusCode() == 400 {
		return token, errors.New("缺少key和secret")
	} else{
		return token, errors.New("获取token请求失败")
	}
}

// 创建一个bucket
func CreateBucket(token string, BucketId string) error {
	//token, tokenErr := GetToken("bucket:create")
	/*
	token, tokenErr := GetToken("data:read data:write data:create viewables:read bucket:read bucket:create")

	if tokenErr != nil {
		return tokenErr
	}
	*/

	req := HttpRequest.NewRequest()
	req.SetHeaders(map[string]string{
		"content-type": "application/json",
		"Authorization": "Bearer " + token,
	})
	resp, err := req.Post(ForgeBucketServer, map[string]interface{}{
		"bucketKey": BucketId,
		"policyKey": "transient",
	})
	if err != nil {
		return err
	}
	if resp.StatusCode() == 200 {
		body, err := resp.Body()
		if err != nil {
			return err
		}
		var response map[string]interface{}
		if jsonErr := json.Unmarshal(body, &response); jsonErr != nil {
			return jsonErr
		}
		if response["bucketKey"].(string) != BucketId {
			return errors.New("创建bucket请求失败")	
		}
		return nil
	}else {
		body, err := resp.Body()
		if err != nil {
			return err
		}
		var response map[string]interface{}
		if jsonErr := json.Unmarshal(body, &response); jsonErr != nil {
			return jsonErr
		}
		return errors.New("创建bucket请求失败:"+response["reason"].(string))	
	}
}

// 获取bucket 信息
func GetBucketInfo(token string, BucketId string) ( error)  {
	//token, tokenErr := GetToken("bucket:read")
	/*
	token, tokenErr := GetToken("data:read data:write data:create viewables:read bucket:read bucket:create")

	if tokenErr != nil {
		return tokenErr
	}
	*/

	url := ForgeBucketServer + "/" + BucketId +"/details"
	req := HttpRequest.NewRequest()
	req.SetHeaders(map[string]string{
		"Authorization": "Bearer "+token,
	})
	resp, err := req.Get(url)
	
	log.Println("resp.StatusCode()", resp.StatusCode())
	if err != nil {
		// 请求失败就直接报错了
		return err
	}

	if resp.StatusCode() == 200 {
		body, _ := resp.Body()
		log.Println(body)
		// 此处未完成
		return nil
	} else {
		return errors.New("请求失败")
	}
}

// 上传文件shell
func ForgeUploadFileCmd(token string, bucketId string, path string, filename string) (ForgeUpdateResult , error) {
	var forgeUpdateResult ForgeUpdateResult
	//token, tokenErr := GetToken("data:write")
	/*
	token, tokenErr := GetToken("data:read data:write data:create viewables:read bucket:read bucket:create")
	if tokenErr != nil {
		log.Println("tokenErr:", tokenErr)
		return forgeUpdateResult, tokenErr
	}
	*/

	
	var cmd *exec.Cmd
	var res []byte
	
	cmd = exec.Command("curl", "-v" , ForgeBucketServer + "/"+ bucketId + "/objects/"+ xid.New().String() + filename, "-X", "PUT", "-H", "Authorization: Bearer "+token, "-H", "Content-Type: text/plain; charset=UTF-8", "-T", path+filename)
	res, err := cmd.Output()
	if err != nil {
		return forgeUpdateResult, err
	}
	//log.Println("res:", string(res))
	JsonTransErr := json.Unmarshal([]byte(string(res)), &forgeUpdateResult)
	if JsonTransErr != nil {
		return forgeUpdateResult, err
	}
	return forgeUpdateResult, nil
}

// 转换模型 -> 上传完成以后执行此步骤
// TODO: forge viewer 有个特性，如果模型转换过一次以后，可以一直复用，所以我必须实验大量新的模型，看是否会出问题
func ForgeTranslateCmd(token string, urn string, workflowId string) (ForgeTranslateResult, error) {
	var forgeTranslateResult ForgeTranslateResult

	//token, tokenErr := GetToken("data:read data:write")
	/*
	token, tokenErr := GetToken("data:read data:write data:create viewables:read bucket:read bucket:create")
	if tokenErr != nil {
		log.Println("tokenErr:", tokenErr)
		return forgeTranslateResult, tokenErr
	}
	*/

	url := Base64UrlSafeEncode([]byte(urn))
	//log.Println("url:", url)
	//log.Println("token:", token)
	
	cmd := exec.Command("curl", "-X", "POST" , "-H", "Authorization: Bearer "+token, "-H", "Content-Type: application/json", "-v" , ForgeAPIServer + "/job", "-d", `{"input":{"urn":"`+url+`"},"output": {"formats":[{"type": "svf","views": ["2d","3d"]}]},"misc":{"workflow":"` + workflowId + `", "workflowAttribute":{"file":"22.ifc","modelId":"xxxsdfsfsf"}}}`)
	//log.Println("my-workflow:", workflowId)
	res, err := cmd.Output()
	if err != nil {
		return forgeTranslateResult, err
	}
	//log.Println("2873 - ForgeTranslateCmd:", string(res))
	jsonErr := json.Unmarshal([]byte(res), &forgeTranslateResult)
	if jsonErr != nil {
		return forgeTranslateResult, jsonErr
	}

	return forgeTranslateResult, nil
}



//TODO: 下载缩略图
//GET :urn/thumbnail
func GetThumbnial(token string, urn string, folderPath string, filename string) error {
	// 获取token
	//token, _ := GetToken("data:read")
	/*
	token, tokenErr := GetToken("data:read data:write data:create viewables:read bucket:read bucket:create")
	if tokenErr != nil {
		log.Println("tokenErr:", tokenErr)
		return tokenErr
	}
	*/

	// 下载请求
	client := &http.Client{}
	requestGet, _ := http.NewRequest("GET", ForgeAPIServer + "/" + urn + "/thumbnail?width=400&height=400", nil)
	requestGet.Header.Add("Authorization", "Bearer "+token)
	resp, respErr := client.Do(requestGet)
	if respErr != nil {
		return respErr
	}

	// 创建文件
	f, fErr := os.Create(path.Join(folderPath, filename))
	if fErr != nil {
		return fErr
	}

	// 灌入文件
	_, err := io.Copy(f, resp.Body)
	if err != nil {
		return err
	}

	return nil
}

//TODO: 删除转换
//DELETE :urn/manifest
func ForgeDeleteTranslateJob(token string, urn string) error {
	//token, _ := GetToken("data:write data:read")
	/*
	token, tokenErr := GetToken("data:read data:write data:create viewables:read bucket:read bucket:create")
	if tokenErr != nil {
		log.Println("tokenErr:", tokenErr)
		return tokenErr
	}
	*/

	req := HttpRequest.NewRequest()
	req.SetHeaders(map[string]string{
		"Authorization": "Bearer "+token,
	})
	reps, repsErr := req.Delete(ForgeAPIServer + "/" + urn+"/manifest")
	if repsErr != nil {
		return repsErr
	}

	if reps.StatusCode() == 200 {
		body, _ := reps.Body()
		var result map[string]interface{}
		if jsonErr := json.Unmarshal(body, &result); jsonErr != nil {
			return jsonErr
		}
		return nil

	} else {
		return errors.New("请求失败")
	}
}

// 获取模型信息
func GetManifest(token string, urn string) (ForgeManifestResult, error) {
	var forgeManifestResult ForgeManifestResult

	//token, tokenErr := GetToken("data:read viewables:read")
	/*
	token, tokenErr := GetToken("data:read data:write data:create viewables:read bucket:read bucket:create")
	if tokenErr != nil {
		log.Println("tokenErr:", tokenErr)
		return forgeManifestResult, tokenErr
	}
	*/

	req := HttpRequest.NewRequest()
	req.SetHeaders(map[string]string{
		"Authorization": "Bearer "+token,
	})	

	reps, err := req.Get(ForgeAPIServer + "/"+urn+"/manifest")

	if err != nil {
		return forgeManifestResult, err
	}

	if reps.StatusCode() == 200 {
		body, _ := reps.Body()
		log.Println(string(body))
		jsonErr := json.Unmarshal([]byte(body), &forgeManifestResult)
		if jsonErr !=nil {
			return forgeManifestResult, err
		}
		return forgeManifestResult, nil
	}
	return forgeManifestResult, nil
}

// 获取元数据列表
func ForgeGetMetadataList(token string, urn string) error {
	//token, _ := GetToken("data:read")
	/*
	token, tokenErr := GetToken("data:read data:write data:create viewables:read bucket:read bucket:create")
	if tokenErr != nil {
		log.Println("tokenErr:", tokenErr)
		return tokenErr
	}
	*/

	req := HttpRequest.NewRequest()
	req.SetHeaders(map[string]string{
		"Authorization": "Bearer "+token,
	})	
	reps, err := req.Get(ForgeAPIServer + "/"+urn+"/metadata")
	if err != nil {
		return err
	}
	if reps.StatusCode() == 200 {
		body, _ := reps.Body()
		log.Println(body)
		// 此处未完成
		return nil
	}else {
		return errors.New("请求失败, 错误码:" +  strconv.Itoa(reps.StatusCode()))
	}
	
}

// 获取元数据属性
func ForgeGetMetadataGuid(token string, urn string, guid string) error {
	//token, _ := GetToken("data:read")
	/*
	token, tokenErr := GetToken("data:read data:write data:create viewables:read bucket:read bucket:create")
	if tokenErr != nil {
		log.Println("tokenErr:", tokenErr)
		return tokenErr
	}
	*/

	req := HttpRequest.NewRequest()
	req.SetHeaders(map[string]string{
		"Authorization": "Bearer "+token,
	})	
	reps, err := req.Get(ForgeAPIServer + "/"+urn+"/metadata/"+guid)
	if err != nil {
		return err
	}

	if reps.StatusCode() == 200 {
		body, _ := reps.Body()
		log.Println(body)
		// 此处未完成
		return nil
	}else {
		return errors.New("请求失败")	
	}
}

type Properties struct {
	Objectid int32 `json:"objectid"`
	Name string `json:"name"`
	ExternalId string `json:"externalId"`
	Properties struct{
		DimentionInfo interface{} `json:"尺寸标注"`
		Structure interface{} `json:"构造"`
		IdentifyData interface{} `json:"标识数据"`
		Other interface{} `json:"其他"`
		MaterialAndDecorate interface{} `json:"材质和装饰"`
		Construct interface{} `json:"结构"`
		Staging interface{} `json:"阶段化"`
		LimitedCondition interface{} `json:"限制条件"`
		Energy interface{} `json:"能量分析"`
	} `json:"properties"` // 不同的模型属性不一样啊，怎么办呢
}

// 获取属性列表
func ForgeGetMetadataGuidProperty(token string, urn string, guid string) ([]Properties, error) {
	var properties []Properties
	
	type ResponseResult struct {
		Data struct {
			Type string `json:"type"` 
			Collection []Properties `json:"collection"`
		} `json:"data"`
	} 

	//token, _ := GetToken("data:read")
	/*
	token, tokenErr := GetToken("data:read data:write data:create viewables:read bucket:read bucket:create")
	if tokenErr != nil {
		log.Println("tokenErr:", tokenErr)
		return properties, tokenErr
	}
	log.Println("token:", token)
	*/

	req := HttpRequest.NewRequest()
	req.SetHeaders(map[string]string{
		"Authorization": "Bearer "+token,
		"x-ads-force": "true",
	})	
	reps, err := req.Get(ForgeAPIServer + "/"+urn+"/metadata/"+guid+"/properties?forceget=true")
	if err != nil {
		return properties, err
	}
	
	if reps.StatusCode() == 200 {
		body, _ := reps.Body()
		log.Println("body", string(body))
		var responseResult ResponseResult
		if jsonErr := json.Unmarshal(body, &responseResult); jsonErr != nil {
			return properties, nil
		}
		return responseResult.Data.Collection, nil
	} else {
		return properties, errors.New("获取属性列表失败, 错误码:"+ strconv.Itoa(reps.StatusCode()))
	}
	
}

func ForgeGetMetadataGuidPropertyCMD(token string, urn string, guid string) ([]Properties, error) {
	var properties []Properties

	type ResponseResult struct {
		Data struct {
			Type string `json:"type"` 
			Collection []Properties `json:"collection"`
		} `json:"data"`
	}

	cmd := exec.Command("curl", 
	"-X", "GET" , 
	"-H", "Authorization: Bearer "+token, 
	"-v" , ForgeAPIServer + "/" + urn +"/metadata/" + guid +"/properties?forceget=true")

	stdout, err := cmd.StdoutPipe()
	if err != nil {
		log.Fatal(err)
		return properties, err
	}
	if err := cmd.Start(); err != nil {
		log.Fatal(err)
		return properties, err
	}
	var responseResult ResponseResult
	if err := json.NewDecoder(stdout).Decode(&responseResult); err != nil {
		log.Fatal(err)
	}
	if err := cmd.Wait(); err != nil {
		log.Fatal(err)
		return properties, err
	}

	return responseResult.Data.Collection, nil
}

func ForgeGetMetadataJsonFilePropertyCMD(token string, urn string, guid string, filepath string) (string,error) {
	cmd := exec.Command("curl", 
	"-X", "GET" , 
	"-H", "Authorization: Bearer "+token, 
	"-v" , ForgeAPIServer + "/" + urn +"/metadata/" + guid +"/properties?forceget=true")
	/*
	stdout, err := cmd.StdoutPipe()
	if err != nil {
		log.Fatal(err)
		return err
	}
	if err := cmd.Start(); err != nil {
		log.Fatal(err)
		return err
	}
	*/
	
	// open the out file for writing
	outfile, err := os.Create(filepath)
	if err != nil {
		log.Fatal(err)
		return "",err
	}
	defer outfile.Close()
	stdoutPipe, err := cmd.StdoutPipe()
	if err != nil {
		log.Fatal(err)
	}


	writer := bufio.NewWriter(outfile)
	defer writer.Flush()

	err = cmd.Start()
	if err != nil {
		log.Fatal(err)
	}
	
	outputBuf1 := bufio.NewReader(stdoutPipe)
	line, _, readlineerr := outputBuf1.ReadLine()
	if readlineerr != nil {
		log.Println("readlineerr:", readlineerr)
	}

	go io.Copy(writer, stdoutPipe)
	cmd.Wait()
	return string(line), nil
}

// 下载文件
// urn : 整个模型的key
// durn : 要下载的那个文件的链接 (childurn)
// basePath: 要存放到本地的路径 /output/Resource/____/3D/
// filename: 文件名
//func ForgeDownloadFile (urn string, durn string, basePath string, filename string) error {
func ForgeDownloadFile (token string, urn string, derivativeurn string, basePath string, svfFile string) error {

	//_, basePath, svfFile := SplitDUrn(derivativeurn)

	//token, _ := GetToken("data:read viewables:read")
	/*
	token, tokenErr := GetToken("data:read data:write data:create viewables:read bucket:read bucket:create")
	if tokenErr != nil {
		log.Println("tokenErr:", tokenErr)
		return tokenErr
	}
	*/

	derivativeurn = EncodeURIComponent(derivativeurn)

	client := &http.Client{}
	requestGet, _ := http.NewRequest("GET", ForgeAPIServer + "/" + urn + "/manifest/" + derivativeurn, nil )
	requestGet.Header.Add("Authorization", "Bearer "+token)
	
	resp, err := client.Do(requestGet)
	if err != nil {
		return err
	}

	isExist, _ := PathExists(basePath)
	if isExist == false {
		os.MkdirAll(basePath, os.ModePerm)
	}

	log.Println("resp.StatusCode:", resp.StatusCode)
	if resp.StatusCode != 200 {
		return errors.New("转换没有成功或没有权限")
	}

	f, err := os.Create(path.Join(basePath, svfFile))
	if err != nil {
		return err
	}

	_, copyErr := io.Copy(f, resp.Body)
	if copyErr != nil {
		return copyErr
	}

	return nil
}

// 解析svf
func ForgeReadSvf(basePath string, name string) (ForgeSVFManifest, error) {
	var forgeSVFManifest ForgeSVFManifest

	cmd2 := exec.Command("unzip", path.Join(basePath, name), "-d", basePath + "/3DManifest")
	_, unzipErr := cmd2.Output()
	if unzipErr != nil {
		return forgeSVFManifest, unzipErr
	}

	// 读取manifest.json
	content, err := ioutil.ReadFile( basePath + "/3DManifest" + "/manifest.json")
	if err != nil {
		return forgeSVFManifest, err
	}

	json.Unmarshal([]byte(content), &forgeSVFManifest)
		
	return forgeSVFManifest, nil
}


// 下载视图文件
// @param baseUrn urn
// @param pathUrl 网络请求的地址
// @param savePath 要保存到本地的地址
func DownloadViewerFile (token string, baseUrn string, pathUrl string, savePath string) error {
	//token, _ := GetToken("viewables:read")
	/*
	token, tokenErr := GetToken("data:read data:write data:create viewables:read bucket:read bucket:create")
	if tokenErr != nil {
		log.Println("tokenErr:", tokenErr)
		return tokenErr
	}
	*/

	client := &http.Client{}
	requestGet, _ := http.NewRequest("GET", ForgeServer + "/" + baseUrn + "/" + pathUrl, nil)
	requestGet.Header.Add("Authorization", "Bearer "+token)

	resp, err := client.Do(requestGet)
	if err != nil {
		return err
	}

	pathUrlArray := strings.Split(savePath, "/")
	pathUrlArray = pathUrlArray[:len(pathUrlArray)-1]
	pathUrlFolder := strings.Join(pathUrlArray, "/")

	isExist, _ := PathExists(pathUrlFolder )
	if isExist == false {
		os.MkdirAll(pathUrlFolder, os.ModePerm)
	}
	log.Println("resp.StatusCode:", resp.StatusCode)
	if resp.StatusCode != 200 {
		return errors.New("转换没有成功或没有权限")
	}
	
	f, err := os.Create(savePath)
	if err != nil {
		return err
	}

	_, copyErr := io.Copy(f, resp.Body)
	if copyErr != nil {
		return err
	}
	return nil
}

// 设置完成callback钩子
// curl -X 'POST' 
//      -v 'https://developer.api.autodesk.com/webhooks/v1/systems/derivative/events/extraction.finished/hooks' 
//      -H 'Content-Type: application/json' 
//      -H 'authorization: Bearer eyJhbGciOiJIUzI1NiIsImtpZCI6Imp3dF9zeW1tZXRyaWNfa2V5In0.eyJzY29wZSI6WyJkYXRhOnJlYWQiLCJkYXRhOmNyZWF0ZSJdLCJjbGllbnRfaWQiOiI4Z3Z6dnlLNndlVEIzUXlrS0hXS0xaSjk3bndxallCNyIsImF1ZCI6Imh0dHBzOi8vYXV0b2Rlc2suY29tL2F1ZC9qd3RleHA2MCIsImp0aSI6IkptNnR1aFc2amkzZWJIOEhDcnhqc2kwNDRKUU1lcXBSUE1TNkFIVDhnZVFhUUdOUFBEc045V1FHSjZIZTNxbEsiLCJleHAiOjE1ODYzMTkwMDJ9.oIr8SOcRXmqDmjw8Eu-NZLaYy0KT024LEun6MfIuMYA' 
//      -d '{"callbackUrl": "http://test.xylab.tech/callback","scope": {"workflow": "my-workflow-id2"}}'

func SetTranslateFinishedHook(token string, workflowId string, callbackUrl string) error {
	//token, _ := GetToken("data:read data:create")
	/*
	token, tokenErr := GetToken("data:read data:write data:create viewables:read bucket:read bucket:create")
	if tokenErr != nil {
		log.Println("tokenErr:", tokenErr)
		return tokenErr
	}
	*/

	cmd := exec.Command("curl", "-X", "POST", "-H", "authorization: Bearer "+token, "-H", "Content-Type: application/json", "-v" , "https://developer.api.autodesk.com/webhooks/v1/systems/derivative/events/extraction.finished/hooks", "-d", `{"callbackUrl": "`+callbackUrl+`","scope": {"workflow": "`+workflowId+`"}}`)
	res, err := cmd.Output()

	if err != nil {
		//return token, err
		log.Println("err:",err)
	}
	
	log.Println("res:", string(res))

	return nil
}

// 设置更新callback钩子
func SetTranslateUpdatedHook(token string, workflowId string, callbackUrl string) error{
	//token, _ := GetToken("data:read data:create")
	/*
	token, tokenErr := GetToken("data:read data:write data:create viewables:read bucket:read bucket:create")
	if tokenErr != nil {
		log.Println("tokenErr:", tokenErr)
		return tokenErr
	}
	*/
	cmd := exec.Command("curl", "-X", "POST", "-H", "authorization: Bearer "+token, "-H", "Content-Type: application/json", "-v" , "https://developer.api.autodesk.com/webhooks/v1/systems/derivative/events/extraction.updated/hooks", "-d", `{"callbackUrl": "`+callbackUrl+`","scope": {"workflow": "`+workflowId+`"}}`)
	res, err := cmd.Output()

	if err != nil {
		//return token, err
		log.Println("err:",err)
	}
	
	log.Println("res:", string(res))

	return nil
}


